<template>
    <div>
        <el-form-item label="价格模式:" v-if="!notShowPriceType">
            <el-select v-model="form.orderPriceType" size="mini" disabled>
                <el-option v-for="i in investPriceSelectData" :key="i.dictKey" :label="i.dictKey + ' ' + i.dictKeyName" :value="i.dictKey">
                </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="当前市价:" :class="['font-color-' + textColor]" class="icon-form-item">
            <el-input v-model="calcPrice" disabled>
                <template slot="append">元</template>
            </el-input>
            <i v-if="!notShowPriceType" class="el-icon-refresh-right" @click="getCalcPrice('1')"></i>
        </el-form-item>
        <el-form-item label="指令价格:">
            <RiskInputNumber
                :disabled="!checkPermission('B_325')"
                :input="form.orderPrice"
                :inputAfter="hkStock ? '港币' : '元'"
                :colorStyle="textColor"
                :precision="2"
                ref="orderPrice"
                :maxlength="10"
                :field="'orderPrice'"
                @getInputNumber="getInputNumber(arguments)"
            >
            </RiskInputNumber>
        </el-form-item>
        <el-row class="form-row" v-if="hkStock" style="width: 100%">
            <span style="float: right; color: #409eff">{{
                cnyOrderPrice && Number(cnyOrderPrice) !== 0 ? String(cnyOrderPrice || '0.00') + '人民币' : '0.00 人民币'
            }}</span>
        </el-row>
        <el-form-item label="指令数量:">
            <RiskInputNumber
                :input="form.orderAmount"
                :inputAfter="'股'"
                :colorStyle="textColor"
                :maxlength="12"
                :precision="2"
                ref="orderAmount"
                :field="'orderAmount'"
                :disabled="targetType == '2'"
                :readonly="!stockCode"
                @getInputNumber="getInputNumber(arguments)"
            >
            </RiskInputNumber>
        </el-form-item>
        <el-form-item label="指令金额:">
            <RiskInputNumber
                :input="form.orderBalance"
                :inputAfter="hkStock ? '港币' : '元'"
                :colorStyle="textColor"
                :precision="2"
                ref="orderBalance"
                :field="'orderBalance'"
                :maxlength="12"
                :disabled="balanceDisabledStatus"
                @getInputNumber="getInputNumber(arguments)"
            >
            </RiskInputNumber>
        </el-form-item>
        <el-col v-if="hkStock" :span="24">
            <span style="float: right; color: #409eff">{{
                cnyOrderBalance && Number(cnyOrderBalance) !== 0 ? cnyOrderBalance + '人民币' : '0.00 人民币'
            }}</span>
        </el-col>
        <el-form-item label="预估中签率:" v-if="buyStock">
            <RiskInputNumber :input="winningRate" :inputAfter="'%'" :maxlength="7" :field="'winningRate'" @getInputNumber="getInputNumber(arguments)">
            </RiskInputNumber>
        </el-form-item>
    </div>
</template>
<script lang="ts">
import Invest from '@/common/dict/invest';
import { objToArr, SGU_CACHE } from '@/utils/diction-const-util';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import RiskInputNumber from '@/pages/risk-measure/components/risk-input-number.vue';
import { Dictionary } from '@/pages/risk-time/types/Dictionary';
import { SelectOptionItemData } from '@/pages/risk-time/types/SelectOptionItemData';
import { checkPermission, convertNum, handleInverseAmount, handleLimitAmount } from '@/utils/tools';

@Component({
    name: 'StockForm',
    components: {
        RiskInputNumber,
    },
})
// 股票指令表单
export default class StockForm extends Vue {
    @Prop()
    hkStock: boolean; // 是否港股股票
    @Prop()
    buyStock: boolean; // 是否申购股票
    @Prop()
    cnyExchangeRate: string; // 汇率
    @Prop()
    stockCode: string;
    @Prop()
    formDetail: any;
    @Prop()
    textColor: string;
    @Prop()
    notMesh: boolean; // 非风险试算页面
    @Prop()
    notShowPriceType: boolean; // 是否显示价格模式(不同页面使用该组件用到该变量)
    @Prop()
    targetType: string; // 目标类型
    @Prop()
    stockInfo: any;
    @Prop()
    refreshNumber: number;
    @Prop()
    changeFlag: string;
    @Prop()
    protectivePrice: any; // 科创板保护价

    checkPermission = checkPermission;

    Invest: any = new Invest();

    orderPrice: string = ''; // 实际指令价格，非显示指令价格

    form = {
        orderPrice: '', // 指令价格
        orderAmount: '', // 指令数量
        orderBalance: '', // 指令金额
        winningRate: '', // 预估中签率
        orderPriceType: '2', // 价格模式
    };

    cnyOrderPrice: string = ''; // 指令价格人民币
    cnyOrderBalance: string = ''; // 指令金额人民币

    calcPrice: number = 0; // 当前市价
    winningRate: string = ''; // 预估中签率
    investPriceSelectData: any[] = []; // 价格模式下拉数据

    @Watch('form', { immediate: true, deep: true })
    setForm() {
        if (this.form.orderPriceType == '2') {
            if (this.calcPrice == null) {
                this.orderPrice = '';
            } else {
                this.orderPrice = this.calcPrice.toString();
            }
        } else {
            this.orderPrice = this.form.orderPrice;
        }
        // 当证券为港股时，传给父组件的价格和金额都是按港币传(传给后端的价格和金额不做乘汇率处理)
        this.$emit(
            'getForm',
            {
                // orderPrice: this.hkStock ? Number(hkOrderPrice).toString() : this.orderPrice,
                // orderBalance: this.hkStock ? Number(this.cnyOrderBalance).toString() : this.form.orderBalance,
                orderPrice: this.orderPrice,
                orderBalance: this.protectivePrice ? this.starMarket.orderBalance : this.form.orderBalance,
                orderAmount: this.protectivePrice ? this.starMarket.orderAmount : this.form.orderAmount, // 指令数量
                winningRate: this.form.winningRate,
                orderPriceType: this.form.orderPriceType,
            },
            'stockValues'
        );
    }

    @Watch('refreshNumber', { immediate: true, deep: true })
    onWatchRefreshNumber() {
        if (this.refreshNumber) {
            if (!this.protectivePrice) {
                this.getCalcPrice('2');
            }
            // this.calcPrice = 12;
            // this.handleOrderPriceChange('');
        }
    }

    @Watch('changeFlag', { immediate: true, deep: true })
    onWatchChangeFlag() {
        if (this.form.orderAmount) {
            if (this.form.orderAmount === '0.00') {
                this.yh_message_warn('指令数量必须大于0！');
                return;
            }
            let limit = handleLimitAmount(this.changeFlag, this.stockInfo, this.form.orderAmount);
            if (!limit) {
                this.form.orderAmount = '';
            }
        }
    }

    get computedCnyExchangeRate() {
        if (this.cnyExchangeRate !== undefined) {
            return this.cnyExchangeRate;
        } else {
            return 1;
        }
    }

    @Watch('formDetail', { immediate: true, deep: true })
    getForm() {
        this.starMarket.orderBalance = this.formDetail.orderBalance;
        this.starMarket.orderAmount = this.formDetail.orderAmount;
        for (const key in this.formDetail) {
            this.form[key] = this.formDetail[key];
        }

        if (this.formDetail.orderPriceType === '2') {
            this.form.orderPrice = '';
            this.orderPrice = this.formDetail.orderPrice;
        }
        if (this.form.winningRate) {
            this.winningRate = (Number(this.form.winningRate) * 100).toString();
        }
    }

    @Watch('stockCode', { immediate: true, deep: true })
    async onWatchStockCode(newValue, oldValue) {
        if (oldValue) {
            this.resetForm();
        }
        await this.getCalcPrice('2');
    }
    starMarket = {
        orderBalance: '',
        orderAmount: '',
    };
    @Watch('protectivePrice', { immediate: true, deep: true })
    watchProtectivePrice(newValue, oldValue) {
        if (newValue) {
            // if (this.form.orderBalance != newValue.instructionBalance || this.form.orderAmount != newValue.instructionAmount) {
            this.form.orderAmount = newValue.instructionAmount;
            this.form.orderBalance = newValue.instructionBalance;
            // }
        }
    }

    async mounted() {
        this.investPriceSelectData = await SGU_CACHE('PriceType', '/dict/list/code/Y_000237', []);
    }

    get balanceDisabledStatus() {
        if (this.targetType == '1') {
            return true;
        } else {
            return false;
        }
    }

    getInputNumber(args: any) {
        let value = args[0];
        let field = args[1];
        if (field !== 'winningRate') {
            this.form[field] = value;
        } else if (value) {
            this.form.winningRate = (Number(value) / 100).toString();
        }
        if (field == 'orderPrice') {
            this.handleOrderPriceChange(value);
        } else if (field == 'orderAmount') {
            setTimeout(() => {
                this.starMarket.orderAmount = this.form.orderAmount;
                this.handleOrderMountChange(value);
            }, 10);
        } else if (field == 'orderBalance') {
            this.starMarket.orderBalance = this.form.orderBalance;
            this.handleOrderBalanceChange(value);
        }
    }

    /**
     * 获取指令价格为空时的计算价格，下面是取值顺序
     * lastPrice: 最新价
     * openPrice: 开盘价
     * closePrice: 昨收盘价
     * facePrice: 面值
     * type: 1-手动刷新(点击刷新图标)，2-自动刷新(切换证券时)
     */
    async getCalcPrice(type: string) {
        if (this.stockCode) {
            await this.$axios
                .post('/dataEngine/getStockPrice/' + this.stockCode)
                .then((result: any) => {
                    this.calcPrice = result.toString();

                    if (this.form.orderPriceType == '2') {
                        this.handleOrderPriceChange('');
                    }

                    if (type == '1') {
                        // if (this.form.orderPriceType == '2') {
                        //     this.handleOrderPriceChange('');
                        // }
                        setTimeout(() => {
                            this.yh_message_success('“当前市价”已刷新！');
                        }, 10);
                    }
                    // 当前市价为0 且 用户未输入指令价格
                    if (!result && !this.form.orderPrice) {
                        this.form.orderPriceType = '1';
                        // handleOrderPriceChange() 方法会执行一次 这里不提示了
                        // this.yh_message_warn('当前证券的“市价”为0，“价格模式”已切换为“限价”，请输入“指令价格”！');

                        this.$nextTick(() => {
                            // 光标定位到“指令价格”的输入框中
                            (this.$refs['orderPrice'] as any).$refs['input'].focus();
                        });
                    }
                })
                .catch(() => {
                    this.calcPrice = null;
                });
        } else {
            this.calcPrice = null;
        }
    }

    handleOrderPriceChange(value: any) {
        let orderAmount;
        // 修改指令价格
        if (value) {
            // 根据输入值计算
            this.form.orderPriceType = '1';
            this.orderPrice = this.form.orderPrice;
            if (this.targetType == '1') {
                if (this.form.orderAmount) {
                    // 绝对数量算金额
                    this.form.orderAmount = (Number(this.form.orderBalance || '0') / Number(this.form.orderPrice || '0')).toFixed(0);
                    (this.$refs.orderAmount as any).dataChange(this.form.orderAmount);
                    // this.form.orderBalance = (Number(this.form.orderAmount || '0') * Number(this.orderPrice)).toFixed(2);
                    // this.form.orderBalance = this.handleVerifyOrderBlance(this.form.orderBalance);
                }
            } else if (this.targetType == '2') {
                if (this.form.orderBalance) {
                    // 绝对金额反推数量
                    this.form.orderAmount = (Number(this.form.orderBalance || '0') / Number(this.orderPrice)).toFixed(0);
                    // 反算指令数量处理
                    this.form.orderAmount = handleInverseAmount(this.changeFlag, this.stockInfo, this.form.orderAmount);
                }
            }
        } else {
            // 当前市价为0 且 用户未输入指令价格
            if (!Number(this.calcPrice) && !this.orderPrice) {
                this.form.orderPriceType = '1';
                this.yh_message_warn('当前证券的“市价”为0，“价格模式”已切换为“限价”，请输入“指令价格”！');
                return;
            }

            this.form.orderPriceType = '2';
            if (this.calcPrice) {
                this.orderPrice = this.calcPrice.toString();
                if (this.form.orderBalance) {
                    if (this.targetType == '1' && !this.protectivePrice) {
                        // 绝对数量算金额
                        this.form.orderBalance = (Number(this.form.orderAmount || '0') * Number(this.calcPrice || '0')).toFixed(2);
                        this.form.orderBalance = this.handleVerifyOrderBlance(this.form.orderBalance);
                        (this.$refs.orderBalance as any).dataChange(this.form.orderBalance);
                    } else if (this.targetType == '2') {
                        // 绝对金额反推数量
                        this.form.orderAmount = (Number(this.form.orderBalance || '0') / Number(this.calcPrice || '0')).toFixed(0);
                        this.form.orderAmount = handleInverseAmount(this.changeFlag, this.stockInfo, this.form.orderAmount);
                    }
                } else if (this.form.orderAmount) {
                    if (this.targetType == '1' && !this.protectivePrice) {
                        // 如果没有金额只有数量，计算金额就行
                        this.form.orderBalance = (Number(this.form.orderAmount || '0') * Number(this.calcPrice || '0')).toFixed(2);
                        this.form.orderBalance = this.handleVerifyOrderBlance(this.form.orderBalance);
                    } else if (this.targetType == '2') {
                    }
                } else {
                    // 金额数量都是空，不做处理
                }
            }
        }
        // this.form.orderAmount = JSON.parse(JSON.stringify(orderAmount
        this.cnyOrderBalance = this.hkToCNY(this.form.orderBalance).toFixed(2).toString();

        this.cnyOrderPrice = this.hkToCNY(this.form.orderPrice).toFixed(2).toString();
    }

    handleOrderMountChange(value: string) {
        let orderBalanceTemp = this.form.orderBalance;
        // 数量不为空，计算市值、计算
        if (value) {
            if (value === '0.00') {
                this.yh_message_warn('指令数量必须大于0！');
                return;
            }
            let limit = handleLimitAmount(this.changeFlag, this.stockInfo, value);
            if (!limit) {
                this.form.orderAmount = '';
            }

            // 如果有价格 并且 没有保护价
            if (this.form.orderPrice) {
                orderBalanceTemp = (Number(this.form.orderAmount || '0') * Number(this.orderPrice || '0')).toFixed(2);
                orderBalanceTemp = this.handleVerifyOrderBlance(orderBalanceTemp);
            } else if (!this.form.orderPrice) {
                if (this.calcPrice) {
                    orderBalanceTemp = (Number(this.form.orderAmount || '0') * Number(this.calcPrice || '0')).toFixed(2);
                    orderBalanceTemp = this.handleVerifyOrderBlance(orderBalanceTemp);
                }
            }
            if (!this.protectivePrice) {
                this.starMarket.orderBalance = orderBalanceTemp;
                this.form.orderBalance = orderBalanceTemp;
                (this.$refs.orderBalance as any).dataChange(this.form.orderBalance);
            } else {
                // 科创板时
                this.starMarket.orderBalance = orderBalanceTemp;
                this.setForm();
            }
        } else {
            // 数量为空 不处理
        }

        this.cnyOrderBalance = this.hkToCNY(this.form.orderBalance).toFixed(2).toString();

        this.cnyOrderPrice = this.hkToCNY(this.form.orderPrice).toFixed(2).toString();
    }

    handleOrderBalanceChange(value: string) {
        let orderAmount = this.form.orderAmount;
        if (this.form.orderPrice) {
            orderAmount = (Number(value || '0') / Number(this.form.orderPrice || '0')).toFixed(0);
        } else {
            if (this.calcPrice) {
                orderAmount = (Number(value || '0') / this.calcPrice).toFixed(0);
            }
        }
        orderAmount = handleInverseAmount(this.changeFlag, this.stockInfo, orderAmount);

        // 根据金额反推指令数量，如果指令数量为空，金额也设置为空
        if (orderAmount === '') {
            this.form.orderBalance = '';
        }
        // 判断指令数量是否是有限数
        if (!Number.isFinite(orderAmount) && !this.orderPrice) {
            this.form.orderPriceType = '1';
            this.form.orderAmount = '';
            this.yh_message_warn('当前证券的“市价”为0，“价格模式”已切换为“限价”，请输入“指令价格”！');
        }

        if (!this.protectivePrice) {
            this.starMarket.orderAmount = orderAmount;
            this.form.orderAmount = orderAmount;
        } else {
            this.starMarket.orderAmount = orderAmount;
            this.setForm();
        }

        this.cnyOrderBalance = this.hkToCNY(this.form.orderBalance).toFixed(2).toString();

        this.cnyOrderPrice = this.hkToCNY(this.form.orderPrice).toFixed(2).toString();
    }

    // 重置表单
    resetForm() {
        this.form.orderPrice = '';
        this.form.orderAmount = '';
        this.form.orderBalance = '';
        this.form.winningRate = '';
        this.form.orderPriceType = '2';
    }

    // 校验指令金额
    handleVerifyOrderBlance(orderBalance: any) {
        if (convertNum(orderBalance) === false || Number(orderBalance) > 999999999999.99) {
            this.yh_message_warn('指令金额不能超过999999999999.99!');
            orderBalance = '';
        }
        return orderBalance;
    }

    /**
     * 将港币转换成人民币
     */
    hkToCNY(hkMoney) {
        let cnyExchangeRate = this.computedCnyExchangeRate;
        return Number(cnyExchangeRate || '0') * Number(hkMoney || '0');
    }

    /**
     * 将人民币转换成港币
     */
    CNYToHK(CNYMoney) {
        if (!isNaN(CNYMoney) && CNYMoney != undefined) {
            let cnyExchangeRate = this.computedCnyExchangeRate;
            console.log(CNYMoney, 'CNYMoney');
            if (Number(CNYMoney || '0') !== 0 && Number(cnyExchangeRate || '0') !== 0) {
                return Number(CNYMoney || '0') / Number(cnyExchangeRate || '0');
            } else {
                return 0;
            }
        }
    }
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-time/styles/order-form';
</style>
